<?php
namespace backend\controllers;

use Yii;
use common\models\Goods;
use common\models\search\GoodsSearch;
use backend\controllers\base\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Goodsfile;
use common\models\Column;
use common\models\GoodsType;
use common\models\Bom;

/**
 * GoodsController implements the CRUD actions for Goods model.
 */
class GoodsController extends BaseController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all Goods models.
     * 
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new GoodsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->orderBy('id desc');
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }

    /**
     * Displays a single Goods model.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id)
        ]);
    }

    /**
     * Creates a new Goods model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * 
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Goods();
        $fmodel = new Goodsfile();
        $parent = Column::find()->asArray()->all();
        $post = Yii::$app->request->post();
        $mpost = $model->load($post);
        $model->setScenario('create');
        $tr=Yii::$app->db->beginTransaction();
        $flag=true;
        if ($mpost) {
            $gsize = [
                'small' => 100,
                'self' => 800,
                'mid' => 440
            ];
            if ($file = $this->upload($model, 'goods', 'logo', $gsize)) {
                $model->logo = '/' . $file;
            }
            $model->create_at = time();
            $model->uid = Yii::$app->user->id;
        }
        if ($mpost && $model->save()) {
            if(!empty($post['GoodsType']['name'])){
                $type=new GoodsType();
                $typeArr=[];
                foreach($post['GoodsType']['name'] as $key=>$val){
                    if($val=='') continue;
                    $typeArr[$key]['id']=null;
                    $typeArr[$key]['gid']=$model->id;
                    $typeArr[$key]['name']=$val;
                    $typeArr[$key]['price']=$post['GoodsType']['price'][$key];
                    
                }
                if(!empty($typeArr)){
                    if(!$this->insertAll($type, $typeArr)){
                        $flag=false;
                    }
                }
            }
            if (! empty($files = $this->upload($fmodel, 'goods', 'name', $gsize, $model->id))) {
                if(!$this->insertAll($fmodel, $files)){
                    $flag=false;
                }
            }
            if($flag){
                $tr->commit();
            }else{
                $tr->rollBack();
            }
            return $this->redirect([
                'index'
            ]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'fmodel' => $fmodel,
                'parent' => $this->dataSort($parent, 'pid')
            ]);
        }
    }
    /**
     * Updates an existing Goods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $fmodel = new Goodsfile();
        $imgs = $fmodel->find()
            ->select('id,name')
            ->where('pid=' . $id)
            ->asArray()
            ->all();
        $parent = Column::find()->asArray()->all();
        $post=Yii::$app->request->post();
        $flag=false;
        $colors=GoodsType::find()->where('gid='.$model->id)->asArray()->all();
        
        if($post){
            $flag=$model->load($post);
            if(!empty($imgs)){
                if(isset($post['Goodsfile']['id'])){
                    $del=array_diff(array_column($imgs,'id'),$post['Goodsfile']['id']);
                    if(!empty($del)){
                        Goodsfile::deleteAll(['in','id',$del]);
                    }
                }else{
                    Goodsfile::deleteAll(['in','id',array_column($imgs,'id')]);
                }
            }
            $gsize = [
                    'small' => 100,
                    'self' => 800,
                    'mid' => 440
                ];
            if (! empty($files = $this->upload($fmodel, 'goods', 'name', $gsize, $model->id))) {
                $this->insertAll($fmodel, $files);
            }

            $type=new GoodsType();
            if(!empty($colors)){
                $cids=array_column($colors,'id');
                if(!empty($post['GoodsType']['id'])){
                    $del=array_diff($cids,$post['GoodsType']['id']);
                    foreach($post['GoodsType']['id'] as $key=>$val){
                        if($type->findOne($val)){
                            $type->name=$post['GoodsType']['name'][$key];
                            $type->price=$post['GoodsType']['price'][$key];
                            $type->save();
                        }
                    }
                    if(!empty($del)){
                        GoodsType::deleteAll(['in','id',$del]);
                    }
                }else{
                   GoodsType::deleteAll(['in','id',$cids]);
                }
            }
            if(!empty($post['GoodsType']['name'])){
                $typeArr=[];
                foreach($post['GoodsType']['name'] as $key=>$val){
                    if($post['GoodsType']['id'][$key]) continue;
                    $typeArr[$key]['id']=null;
                    $typeArr[$key]['gid']=$model->id;
                    $typeArr[$key]['name']=$val;
                    $typeArr[$key]['price']=$post['GoodsType']['price'][$key];
            
                }
                if(!empty($typeArr)){
                    $this->insertAll($type, $typeArr);
                }
            }
            if(isset($_FILES['Goods']['error']['logo']) && $_FILES['Goods']['error']['logo']==0){
               
                if ($file = $this->upload($model, 'goods', 'logo', $gsize)) {
                    $model->logo = '/' . $file;
                }
            }else{
                unset($model->logo);
            }
        }
        if ($flag && $model->save()) {
            return $this->redirect([
                'index',
            ]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'fmodel' => $fmodel,
                'parent' => $this->dataSort($parent, 'pid'),
                'imgs' => $imgs,
                'colors'=>$colors
            ]);
        }
    }

    /**
     * Deletes an existing Goods model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        
        return $this->redirect([
            'index'
        ]);
    }

    public function updateData($data)
    {}

    /**
     * Finds the Goods model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * 
     * @param integer $id            
     * @return Goods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Goods::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
